package cn.kgc.springmvc.day03.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2024/7/22
 * @description   springmvc中如何处理cookie和session的值
 *
 * http请求无状态请求协议   /user/delete    权限  合法用户   -> interface
 *   A    login     /user/delete     放行
 *
 *   B    未认证    /user/delete     拦截

 * cookie:    自动创建cookie  生成在服务端保存在客户端的数据    响应给浏览器     JSESSIONID:11D16F13A3744EA00AD38F44179752B0
 *
 * session:   /user/login  ->  session  会话   sessionID:11D16F13A3744EA00AD38F44179752B0
 *
 *
 * @SessionAttribute
 * @CookieValue
 */
@Controller
@RequestMapping("cs")
public class CSController {

    @GetMapping("m1")
    public String  method1(HttpSession session){
        String id = session.getId();
        System.out.println("id = " + id);
        session.setAttribute("authorization","login");
        return "user";
    }

    @GetMapping("m2")
    public String  method2(HttpSession session){
        String id = session.getId();
        System.out.println("id = " + id);
        String message = (String) session.getAttribute("authorization");
        System.out.println("message = " + message);
        return "user";
    }

    //  session的处理
    @GetMapping("m3")
    public String  method3(@SessionAttribute("authorization") String message){

        System.out.println("message = " + message);
        return "user";
    }

    // 自定义cookie 响应给浏览器
    @GetMapping("m4")
    public String  method4(HttpServletResponse response){
        // JSESSIONID
        Cookie cookie = new Cookie("username", "jack");
        cookie.setPath("/");
        // cookie.setMaxAge();
        response.addCookie(cookie);
        return "user";
    }

    @GetMapping("m5")
    public String  method5(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("username".equals(name)){       // username
                String value = cookie.getValue();
                System.out.println("value = " + value);
            }
        }
        return "user";
    }


    @GetMapping("m6")
    public String  method6(@CookieValue("username") String ckValue){

        System.out.println("ckValue = " + ckValue);

        return "user";
    }

}
